import { defineStore } from 'pinia'
import { ref, computed } from 'vue'
import { formatDate, isSameDay } from '../utils/dateUtils'

export const useHistoryStore = defineStore('history', () => {
  // 状态定义
  const historyList = ref([])
  const loading = ref(false)
  
  // 配置常量
  const MAX_HISTORY_COUNT = 100 // 最大历史记录数量
  const STORAGE_KEY = 'browse_history'

  // 计算属性
  const historyCount = computed(() => historyList.value.length)
  const isEmpty = computed(() => historyList.value.length === 0)
  const hasHistory = computed(() => historyList.value.length > 0)

  // 获取最近访问的文章（前10条）
  const recentHistory = computed(() => historyList.value.slice(0, 10))

  // Actions
  const initHistory = () => {
    try {
      const savedHistory = localStorage.getItem(STORAGE_KEY)
      if (savedHistory) {
        const parsedHistory = JSON.parse(savedHistory)
        // 验证数据格式
        if (Array.isArray(parsedHistory)) {
          historyList.value = parsedHistory
          console.log(`恢复浏览历史数据: ${historyList.value.length} 条`)
        }
      }
    } catch (error) {
      console.error('初始化浏览历史失败:', error)
      historyList.value = []
    }
  }

  const saveHistory = () => {
    try {
      localStorage.setItem(STORAGE_KEY, JSON.stringify(historyList.value))
    } catch (error) {
      console.error('保存浏览历史失败:', error)
    }
  }

  // 添加浏览记录
  const addHistory = (articleData) => {
    try {
      if (!articleData || !articleData.news_id) {
        console.warn('无效的文章数据，无法添加到浏览历史')
        return false
      }

      const newsId = articleData.news_id
      const now = Date.now()

      // 创建历史记录对象
      const historyItem = {
        id: newsId,
        title: articleData.title || '无标题',
        summary: generateSummary(articleData.content_text || articleData.content_html || ''),
        category: articleData.category || '',
        section: articleData.section || '',
        publishTime: articleData.pub_time || articleData.pubTime || null,
        visitTime: now,
        thumbnail: extractThumbnail(articleData.content_html || ''),
        url: articleData.url || ''
      }

      // 检查是否已存在相同文章
      const existingIndex = historyList.value.findIndex(item => 
        item.id === newsId || String(item.id) === String(newsId)
      )

      if (existingIndex > -1) {
        // 如果已存在，更新访问时间并移到最前面
        historyList.value.splice(existingIndex, 1)
        console.log(`更新已存在的浏览记录: ${articleData.title}`)
      } else {
        console.log(`添加新的浏览记录: ${articleData.title}`)
      }

      // 添加到列表开头
      historyList.value.unshift(historyItem)

      // 限制历史记录数量
      if (historyList.value.length > MAX_HISTORY_COUNT) {
        const removed = historyList.value.splice(MAX_HISTORY_COUNT)
        console.log(`删除过期的浏览记录: ${removed.length} 条`)
      }

      // 保存到localStorage
      saveHistory()
      
      return true
    } catch (error) {
      console.error('添加浏览历史失败:', error)
      return false
    }
  }

  // 生成文章摘要
  const generateSummary = (content, maxLength = 100) => {
    if (!content) return ''
    
    // 移除HTML标签
    const textContent = content.replace(/<[^>]*>/g, '')
    
    // 移除多余的空白字符
    const cleanText = textContent.replace(/\s+/g, ' ').trim()
    
    // 截取指定长度
    if (cleanText.length <= maxLength) {
      return cleanText
    }
    
    return cleanText.substring(0, maxLength) + '...'
  }

  // 提取缩略图
  const extractThumbnail = (htmlContent) => {
    if (!htmlContent) return ''
    
    // 使用正则表达式提取第一张图片
    const imgMatch = htmlContent.match(/<img[^>]+src="([^"]+)"[^>]*>/i)
    if (imgMatch && imgMatch[1]) {
      return imgMatch[1]
    }
    
    return ''
  }

  // 删除单条历史记录
  const removeHistory = (newsId) => {
    try {
      const index = historyList.value.findIndex(item => 
        item.id === newsId || String(item.id) === String(newsId)
      )
      
      if (index > -1) {
        const removed = historyList.value.splice(index, 1)
        saveHistory()
        console.log(`删除浏览记录: ${removed[0].title}`)
        return true
      }
      
      return false
    } catch (error) {
      console.error('删除浏览记录失败:', error)
      return false
    }
  }

  // 批量删除历史记录
  const removeHistories = (newsIds) => {
    try {
      let removedCount = 0
      
      newsIds.forEach(newsId => {
        if (removeHistory(newsId)) {
          removedCount++
        }
      })
      
      return removedCount
    } catch (error) {
      console.error('批量删除浏览记录失败:', error)
      return 0
    }
  }

  // 清除所有历史记录
  const clearAllHistory = () => {
    try {
      historyList.value = []
      localStorage.removeItem(STORAGE_KEY)
      console.log('已清除所有浏览历史')
      return true
    } catch (error) {
      console.error('清除浏览历史失败:', error)
      return false
    }
  }

  // 获取指定文章的历史记录
  const getHistoryItem = (newsId) => {
    return historyList.value.find(item => 
      item.id === newsId || String(item.id) === String(newsId)
    )
  }

  // 检查文章是否在历史记录中
  const isInHistory = (newsId) => {
    return historyList.value.some(item => 
      item.id === newsId || String(item.id) === String(newsId)
    )
  }

  // 获取分页历史记录
  const getHistoryByPage = (page = 1, pageSize = 20) => {
    const startIndex = (page - 1) * pageSize
    const endIndex = startIndex + pageSize
    
    return {
      list: historyList.value.slice(startIndex, endIndex),
      total: historyList.value.length,
      page,
      pageSize,
      hasMore: endIndex < historyList.value.length
    }
  }

  // 按日期分组获取历史记录
  const getHistoryGroupedByDate = () => {
    const groups = {}
    const today = new Date()
    const yesterday = new Date(today.getTime() - 24 * 60 * 60 * 1000)
    
    historyList.value.forEach(item => {
      const visitDate = new Date(item.visitTime)
      let groupKey = ''
      
      if (isSameDay(visitDate, today)) {
        groupKey = '今天'
      } else if (isSameDay(visitDate, yesterday)) {
        groupKey = '昨天'
      } else {
        groupKey = formatDate(visitDate)
      }
      
      if (!groups[groupKey]) {
        groups[groupKey] = []
      }
      groups[groupKey].push(item)
    })
    
    return groups
  }

  // 辅助函数已移至 @/utils/dateUtils.js

  // 搜索历史记录
  const searchHistory = (keyword) => {
    if (!keyword || keyword.trim() === '') {
      return historyList.value
    }
    
    const searchTerm = keyword.toLowerCase().trim()
    
    return historyList.value.filter(item => 
      item.title.toLowerCase().includes(searchTerm) ||
      item.summary.toLowerCase().includes(searchTerm) ||
      item.category.toLowerCase().includes(searchTerm) ||
      item.section.toLowerCase().includes(searchTerm)
    )
  }

  // 初始化时自动恢复历史数据
  initHistory()

  return {
    // 状态
    historyList,
    loading,
    
    // 计算属性
    historyCount,
    isEmpty,
    hasHistory,
    recentHistory,
    
    // Actions
    initHistory,
    addHistory,
    removeHistory,
    removeHistories,
    clearAllHistory,
    getHistoryItem,
    isInHistory,
    getHistoryByPage,
    getHistoryGroupedByDate,
    searchHistory
  }
})
